<template>
  <a-drawer
    v-model:visible="vdata.drawerVisible"
    :mask-closable="false"
    :title=" vdata.isAdd ? '新增设备' : '修改设备' "
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <a-form v-if="vdata.drawerVisible" ref="infoFormModel" :model="vdata.saveObject" layout="horizontal" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="24">
          <a-form-item label="选择设备型号" name="provider">
            <a-select v-model:value="vdata.saveObject.provider" placeholder="请选择设备型号">
              <a-select-option value="alipayRuYi">如意Lite (SN：<b>FZ</b> 开头)</a-select-option>
              <a-select-option value="alipayRuYiPro">如意Lite升级款 (SN：<b>MG</b> 开头)</a-select-option>
              <a-select-option value="alipayRuYi2">如意Lite2.0 (SN：<b>LD</b> 开头)</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.isAdd" :span="24">
          <a-form-item label="批次号" name="batchId">
            <a-input v-model:value="vdata.saveObject.batchId" placeholder="请输入批次号" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row v-if="!vdata.isAdd" justify="space-between" type="flex">
        <a-col :span="16">
          <a-form-item label="设备名称" name="deviceName">
            <a-input v-model:value="vdata.saveObject.deviceName" placeholder="请输入设备名称" />
          </a-form-item>
        </a-col>
        <a-col :span="16" justify="space-between" type="flex">
          <a-form-item label="设备号" name="deviceNo">
            <a-input v-model:value="vdata.saveObject.deviceNo" placeholder="请输入设备号" />
          </a-form-item>
        </a-col>
      </a-row>

      <template v-if="vdata.isAdd">
        <a-col :span="24">
          <a-form-item label="">
            <a-radio-group v-model:value="vdata.deviceInputMode">
              <a-radio :value="1">逐条添加</a-radio>
              <a-radio :value="2">批量添加</a-radio>
            <!-- <a-radio :value="3">导入Excel</a-radio> -->
            </a-radio-group>
          </a-form-item>
        </a-col>

        <!-- 逐条输入 -->
        <template v-if="vdata.deviceInputMode == 1">
          <a-row v-for="(item, index) in vdata.saveObject.deviceList" :key="index" justify="start" type="flex" :gutter="8">
            <a-col :span="10" style="margin-right: 15px;">
              <a-form-item
                layout="vertical"
                label="设备号"
                :name="['deviceList', index, 'deviceNo']"
                :rules="{
                  required: true,
                  message: '设备号不能为空',
                  trigger: 'blur',
                }"
              >
                <a-input v-model:value="item.deviceNo" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-button v-if="index >= 1" danger type="link" @click="removeDomain(item)"><MinusCircleOutlined class="delete-button" /></a-button>
          </a-row>
          <a-col :span="24">
            <a-form-item>
              <a-button type="dashed" @click="addDomain"><PlusOutlined />新增</a-button>
            </a-form-item>
          </a-col>
        </template>

        <!-- 批量输入 -->
        <a-row v-if="vdata.deviceInputMode == 2" justify="start" type="flex">
          <a-col :span="24">
            <a-form-item label="设备号">
              <a-textarea v-model:value="vdata.deviceTextarea" :rows="8" placeholder="请输入" />
              <div class="jeepay-tip-text" style="display: flex;flex-direction: column">
                <span>多设备号之间以英文逗号隔开，例如：111,222,333</span>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </template>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { API_URL_STORE_DEVICE, req } from '@/api/manage'
import { defineProps, getCurrentInstance, reactive, ref } from 'vue'

  const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
 
  const props = defineProps({
    callbackFunc: { type: Function, default:null }
  })

  const infoFormModel = ref()

  const  vdata = reactive({
    btnLoading: false,
    isAdd: true, // 新增 or 修改页面标志

    deviceInputMode: 1, // 设备号输入方式：1-逐条 2-批量
    deviceTextarea: '', // 批量输入设备号model

    saveObject: {} as any, // 数据对象
    recordId: null, // 更新对象ID
    drawerVisible: false, // 是否显示弹层/抽屉
    rules: {
      deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
      deviceNo: [{ required: true, message: '请输入设备号', trigger: 'blur' }]
    }
  }) as any


  function show (record: any) { // 弹层打开事件
    vdata.isAdd = !record.deviceId

    vdata.saveObject = { deviceType: record.deviceType, 'state': 1, deviceList: [{ deviceNo: '' }] }

    if (infoFormModel.value != undefined) {
      infoFormModel.value.resetFields()
    }

    if (!vdata.isAdd) { // 修改信息 延迟展示弹层
      vdata.recordId = record.deviceId

      req.getById(API_URL_STORE_DEVICE, vdata.recordId).then((res: any) => {
        vdata.saveObject = res
      })
    }

    vdata.drawerVisible = true // 立马展示弹层信息
  }

   // 保存
  function  handleOkFunc () {
    infoFormModel.value.validate().then((valid: any) =>{
      vdata.btnLoading = true

      // 请求接口
      if (vdata.isAdd) {

        // 设备号赋值，以 , 隔开的字符串
        vdata.saveObject.deviceNoParams = vdata.deviceTextarea
        if (vdata.deviceInputMode == 1) {
          vdata.saveObject.deviceNoParams = vdata.saveObject.deviceList.map((item) => {
            return item.deviceNo
          }).join(',')
        }

        req.add(API_URL_STORE_DEVICE, vdata.saveObject).then((res: any) => {
          successFunc('保存成功')
        }).catch((err: any) => {
          vdata.btnLoading = false
        })

      } else {
        const { provider, deviceNo, deviceName } = vdata.saveObject
        req.updateById(API_URL_STORE_DEVICE, vdata.recordId, { provider, deviceNo, deviceName }).then((res: any) => {
          successFunc('修改成功')
        }).catch((err: any) => {
          vdata.btnLoading = false
        })
      }
    })
  }

  function successFunc(e: string) { // 新增/更新成功
    vdata.btnLoading = false
    $infoBox.message.success(e)
    props.callbackFunc()
    vdata.drawerVisible = false
  }

  function  onClose () { // 关闭抽屉
    vdata.drawerVisible = false
  }

  function addDomain() {
  vdata.saveObject.deviceList.push({
    deviceNo: ''
  })
}

function removeDomain(item) {
  const index = vdata.saveObject.deviceList.indexOf(item)
  if (index != -1) {
    vdata.saveObject.deviceList.splice(index, 1)
  }
}

defineExpose({
  show
})
</script>
